#include "hal_current.h"
#include "hal_configer.h"
#include "hal_driver.h"
#include "hal_temp.h"
#include "math.h"
#include "common.h"
#include "hal_tlv.h"
#include "sys_log.h"

float volSet = 0;
float taCurCal = 0;
float taVolSet = 0;
float seedVolSet = 0;


float seedVol = 0;

float taVol = 0;

float pdCurAdj = 0;

float taCurAdj = 0;

float taVolSetTemp = 0;

float taCurTempFunc = 0;

void hal_CurrentInit(){
    // 通道一电流
    hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED,LASER_NUMBER_CHAN_1);

#if MODEL_CHOICE == MODEL_LASER_TA
    // 通道二电流
    //hal_PDCurrentSlowChange(0, LASER_NUMBER_CHAN_2);
		hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED,LASER_NUMBER_CHAN_2);
		//hal_TACurrentSlowChange(0, SAMPCUR_TYPE_WORK_CURRENT);
#elif MODEL_CHOICE == MODEL_LASER_DFB
    // 通道二电流
    hal_SeedCurrentSlowChange(0, CURRENT_SEPARAT_SEED, LASER_NUMBER_CHAN_2);
#endif
}


//TA工作电流设置直接从这里，需要判断splitCurrent
/*void hal_SeedCurrentSlowChange(float TargetCurrent, int SplitCurrent){
		
    float NowCurrent = HAL_ADC1119I2cReadCurrentReal(LASER_NUMBER_CHAN_1, SAMPCUR_TYPE_WORK_CURRENT);

    if (!hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_SEED, NowCurrent, LASER_NUMBER_CHAN_1))
    {
        SLOG_I("laser number:%d hal_SeedCurrentSlowChange read nowcurrent error: %f \t\r\n", LASER_NUMBER_CHAN_1, NowCurrent);
        return;
    }

    // 步长基准
    int StepCurrent = CURRENT_STEP_BASE;

    float current = NowCurrent;

    if (NowCurrent > TargetCurrent)
        StepCurrent *= -1;

    // 如果目标电流和设置电流相等，直接输出设置电流
    if (NowCurrent != TargetCurrent)
    {
        // 逐步增加电流并模拟过程
        for (int step = 0; step < (ceil)(fabs(TargetCurrent - NowCurrent)); ++step)
        {
            // 升电流
            if (StepCurrent > 0)
            {
                if ((current + CURRENT_STEP_BASE) >= TargetCurrent)
                {
                    hal_SeedCurrentDirectChange(TargetCurrent,SAMPCUR_TYPE_WORK_CURRENT);
                    break;
                }
            }
            // 降电流
            else
            {
                // 避免0.6不满足0，current会继续-1，导致-0.4也会被输出
                // 负数会直接转换为6553X，导致电流骤增，进而导致OCP，电流超调触发硬件电流保护，从而发送0x02的错误码
                // +1可以在0.6的时候就满足，从而输出目标值TargetCurrent：0
                if (current <= (TargetCurrent + CURRENT_STEP_BASE))
                {
                    hal_SeedCurrentDirectChange(TargetCurrent,SAMPCUR_TYPE_WORK_CURRENT);
                    break;
                }
            }

            // 分割点之前的步骤，增加电流量为 1 / -1     分割点之后的步骤，增加电流量为 2/-2

						
						current += ((current < SplitCurrent) ? CURRENT_STEP_UNDER_60_SEED : CURRENT_STEP_ABOVE_60_SEED) * StepCurrent;
						


            hal_SeedCurrentDirectChange(current,SAMPCUR_TYPE_WORK_CURRENT);
        }
    }
    else
    {
        hal_SeedCurrentDirectChange(TargetCurrent,SAMPCUR_TYPE_WORK_CURRENT);
    }
}*/

/*void hal_SeedCurrentDirectChange(float TargetCurrent,SampCurTypeEn SampCurType){
    if (hal_LaserWriteValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_SEED, TargetCurrent, LASER_NUMBER_CHAN_1))
    {
        HAL_DAC5541SpiWriteCurrentReal(fabs(TargetCurrent), LASER_NUMBER_CHAN_1, SampCurType);
        // fixbyme : 20ms是必须的吗
        systick_delay_ms(MS1_NUM);
    }
}*/

void hal_SeedCurrentSlowChange(float TargetCurrent, int SplitCurrent, int LaserNumber)
{
    float NowCurrent = HAL_ADC1119I2cReadCurrentReal(LaserNumber, SAMPCUR_TYPE_WORK_CURRENT);

    /*if (!hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_SEED, NowCurrent, LaserNumber))
    {
        SLOG_I("laser number:%d hal_SeedCurrentSlowChange read nowcurrent error: %f \t\r\n", LaserNumber, NowCurrent);
        return;
    }*/

    // 步长基准
    int StepCurrent = CURRENT_STEP_BASE;

    float current = NowCurrent;

    if (NowCurrent > TargetCurrent)
        StepCurrent *= -1;

    // 如果目标电流和设置电流相等，直接输出设置电流
    if (NowCurrent != TargetCurrent)
    {
        // 逐步增加电流并模拟过程
        for (int step = 0; step < (ceil)(fabs(TargetCurrent - NowCurrent)); ++step)
        {
            // 升电流
            if (StepCurrent > 0)
            {
                if ((current + CURRENT_STEP_BASE) >= TargetCurrent)
                {
                    hal_SeedCurrentDirectChange(TargetCurrent, LaserNumber);
                    break;
                }
            }
            // 降电流
            else
            {
                // 避免0.6不满足0，current会继续-1，导致-0.4也会被输出
                // 负数会直接转换为6553X，导致电流骤增，进而导致OCP，电流超调触发硬件电流保护，从而发送0x02的错误码
                // +1可以在0.6的时候就满足，从而输出目标值TargetCurrent：0
                if (current <= (TargetCurrent + CURRENT_STEP_BASE))
                {
                    hal_SeedCurrentDirectChange(TargetCurrent, LaserNumber);
                    break;
                }
            }

            // 分割点之前的步骤，增加电流量为 1 / -1     分割点之后的步骤，增加电流量为 2/-2
						if(LaserNumber == LASER_NUMBER_CHAN_1){
							current += ((current < SplitCurrent) ? CURRENT_STEP_UNDER_60_SEED : CURRENT_STEP_ABOVE_60_SEED) * StepCurrent;
						}
						if(LaserNumber == LASER_NUMBER_CHAN_2){
							current += ((current < SplitCurrent) ? CURRENT_STEP_UNDER_1000_TA : CURRENT_STEP_ABOVE_1000_TA) * StepCurrent;
						}

            hal_SeedCurrentDirectChange(current, LaserNumber);
        }
    }
    else
    {
        hal_SeedCurrentDirectChange(TargetCurrent, LaserNumber);
    }
}

void hal_SeedCurrentDirectChange(float TargetCurrent, int LaserNumber)
{
    //if (hal_LaserWriteValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_SEED, TargetCurrent, LaserNumber))
    //{
        HAL_DAC5541SpiWriteCurrentReal(fabs(TargetCurrent), LaserNumber);
        // fixbyme : 20ms是必须的吗
        systick_delay_ms(MS1_NUM);
    //}
}


//从7689获取pd电流
void hal_TACurrentSlowChange(float targetCurrent,SampCurTypeEn SampCurType){
	float nowCurrent = 0;
	int stepCurrent = 0;
	float targetCur = 0;
	
	if(SampCurType == SAMPCUR_TYPE_WORK_CURRENT){
		nowCurrent = HAL_ADC1119I2cReadCurrentReal(LASER_NUMBER_CHAN_2, SAMPCUR_TYPE_WORK_CURRENT);//这里返回的在数值上进行统一
		stepCurrent = CURRENT_STEP_BASE_TA;
		targetCur = targetCurrent;
	}else{
		nowCurrent = HAL_AD7689SpiReadTempOrTempCtrCurReal(ADC7689_LASER_PDPOWER_CHAN_2, AD7689_LASER_PDPOWER_REGTOT, LASER_NUMBER_CHAN_2) * 1000;
		stepCurrent = CURRENT_STEP_BASE_TA;
		targetCur = targetCurrent * 1000;
	}
	
  float current = nowCurrent;
	if (nowCurrent > targetCur)
		stepCurrent *= -1;
	
	// 如果目标电流和设置电流相等，直接输出设置电流
  if (nowCurrent != targetCur)
  {
      // 逐步增加电流并模拟过程
      for (int step = 0; step < (ceil)(fabs(targetCur - nowCurrent)); ++step)
      {
          // 升电流
          if (stepCurrent > 0)
          {
              if ((current + CURRENT_STEP_BASE_TA) >= targetCur)
              {
                  hal_TACurrentDirectChange(targetCur,SAMPCUR_TYPE_WORK_CURRENT);
                  break;
              }
          }
          // 降电流
          else
          {
              // 避免0.6不满足0，current会继续-1，导致-0.4也会被输出
              // 负数会直接转换为6553X，导致电流骤增，进而导致OCP，电流超调触发硬件电流保护，从而发送0x02的错误码
              // +1可以在0.6的时候就满足，从而输出目标值TargetCurrent：0
              if (current <= (targetCur + CURRENT_STEP_BASE_TA))
              {
                  hal_TACurrentDirectChange(targetCur,SAMPCUR_TYPE_WORK_CURRENT);
                  break;
              }
          }

          // 分割点之前的步骤，增加电流量为 1 / -1  分割点之后的步骤，增加电流量为 2/-2
					
					current += ((current < 1000) ? CURRENT_STEP_UNDER_1000_TA : CURRENT_STEP_ABOVE_1000_TA) * stepCurrent;	

          hal_TACurrentDirectChange(current,SAMPCUR_TYPE_WORK_CURRENT);
       }
    }
    else
    {
        hal_TACurrentDirectChange(targetCur,SAMPCUR_TYPE_WORK_CURRENT);
    }
	
}

void hal_TACurrentDirectChange(float targetCurrent,SampCurTypeEn SampCurType){
	/*if(hal_LaserWriteValueNormal(JUDGE_LASER_LIMIT_TYPE_CURRENT_TA,TargetCurrent,LaserNumber)){
		HAL_DAC5541SpiWriteCurrentReal(fabs(TargetCurrent),LaserNumber);
		systick_delay_ms(MS1_NUM);
	}*/
	
	if(SampCurType == SAMPCUR_TYPE_WORK_CURRENT){
		//HAL_DAC5541SpiWriteCurrentReal(fabs(targetCurrent),LASER_NUMBER_CHAN_2,SAMPCUR_TYPE_WORK_CURRENT);
		systick_delay_ms(MS1_NUM);
	}else{
		//PD的话需要在这里除1000，进行设置
		float tarCur = targetCurrent / 1000;
		//HAL_DAC5541SpiWriteCurrentReal(fabs(tarCur),LASER_NUMBER_CHAN_2,SAMPCUR_TYPE_PD_CURRENT);
		systick_delay_ms(MS1_NUM);
	}
}


//以下原pd设置TA电流
/*
void hal_PDCurrentSlowChange(float TargetCurrent){
    //float NowCurrent = HAL_AD7689SpiReadTempOrTempCtrCurReal(ADC7689_LASER_PDPOWER_CHAN_2, AD7689_LASER_PDPOWER_REGTOT, LASER_NUMBER_CHAN_2);
	
		HAL_DAC5541SpiWriteCurrentReal(0,LASER_NUMBER_CHAN_2);
		
	pdCurAdj = NowCurrent;
	
    if (!hal_LaserReadValueNormal(JUDGE_LASER_LIMIT_TYPE_PD, NowCurrent, LASER_NUMBER_CHAN_2))
    {
        SLOG_I("laser number:%d hal_PDCurrentSlowChange read nowcurrent error: %f \t\r\n", LASER_NUMBER_CHAN_2, NowCurrent);
        return;
    }

    // 步长基准
    float StepCurrent = CURRENT_PD_STEP_PD;

    float current = NowCurrent;

    if (NowCurrent > TargetCurrent)
        StepCurrent *= -1;

    // 如果目标电流和设置电流相等，直接输出设置电流
    if (NowCurrent != TargetCurrent)
    {
        // 逐步增加电流并模拟过程
        for (int step = 0; step < (ceil)(fabs(TargetCurrent - NowCurrent) / CURRENT_PD_STEP_PD); ++step)
        {
            // 升电流
            if (StepCurrent > 0)
            {
                if ((current + CURRENT_PD_STEP_PD) >= TargetCurrent)
                {
                    hal_PDCurrentDirectChange(TargetCurrent, LASER_NUMBER_CHAN_2);
                    break;
                }
            }
            // 降电流
            else
            {
                if (current <= (TargetCurrent + CURRENT_PD_STEP_PD))
                {
                    hal_PDCurrentDirectChange(TargetCurrent, LASER_NUMBER_CHAN_2);
                    break;
                }
            }

            current += StepCurrent;

            hal_PDCurrentDirectChange(current, LASER_NUMBER_CHAN_2);
        }
    }
    else
    {
        hal_PDCurrentDirectChange(TargetCurrent, LASER_NUMBER_CHAN_2);
    }
}

void hal_PDCurrentDirectChange(float TargetCurrent){
    //if (hal_LaserWriteValueNormal(JUDGE_LASER_LIMIT_TYPE_PD, TargetCurrent, LaserNumber))
    //{
        HAL_DAC5541SpiWriteCurrentReal(fabs(TargetCurrent), LASER_NUMBER_CHAN_2);
        // fixbyme : 20ms是必须的吗
        systick_delay_ms(MS1_NUM);
    //}
}




*/



float hal_ADS1119I2cCurrentRegtomA(uint16_t current_V, int LaserNumber, SampCurTypeEn SampCurType){
		//拿电压出来看一下
    int16_t CurrentReadReg = current_V;

#if MODEL_CHOICE == MODEL_LASER_TA
    // ADC1119对于种子和TA有不同的电阻和增益系数
    // 种子的电阻：10欧姆，增益系数1
    // TA的电阻：0.05欧姆，增益系数10
    // PD的电阻：300欧姆
    // *1000 转换为mV，result 单位为mA
    float CurrentVolage = (float)CurrentReadReg /ADS1119_MAXCODE * ((LaserNumber == LASER_NUMBER_CHAN_1) ? ADS1119_VREF_CHAN_1 : ADS1119_VREF_CHAN_2);
		
		if(LaserNumber == LASER_NUMBER_CHAN_1 && SampCurType == SAMPCUR_TYPE_WORK_CURRENT)
			seedVol = CurrentVolage;
		
		//这里的单位未统一，获取到的pd值是uA
		float result = (float)(CurrentVolage / ((LaserNumber == LASER_NUMBER_CHAN_1) ? (ADDA_R_SEED * ADDA_GAIN_SEED * 0.001)
                                   : (SampCurType == SAMPCUR_TYPE_WORK_CURRENT) ? (ADDA_R_TA * ADDA_GAIN_TA * 0.001) : ADDA_R_PD ));
#elif MODEL_CHOICE == MODEL_LASER_DFB
    float CurrentVolage = (float)CurrentReadReg / ADS1119_MAXCODE * ADS1119_VREF_CHAN_1;
    float result        = (float)(CurrentVolage / (ADDA_R_SEED * ADDA_GAIN_SEED) * 1000);
#endif
		
		//拿出来看一下
		//这里不存在work还是pd的判断
		if(LaserNumber == LASER_NUMBER_CHAN_2 && SampCurType == SAMPCUR_TYPE_WORK_CURRENT){
			taVol = CurrentVolage;
			taCurAdj = result;
		}

    if (result < 0)
    {
        return 0;
    }
    else
    {
        //return CurrentVolage;
				return result;
    }
}



/*uint16_t hal_DAC5541SpiCurrentmAToReg(float Current, int LaserNumber,SampCurTypeEn SampCurType){
		uint16_t currentWriteReg = 0;
	// DAC5541的输出分种子和TA
	// 种子的电阻：10欧姆
	// TA的电阻：300欧姆
	
#if MODEL_CHOICE == MODEL_LASER_TA
		if(Current == 0){
			currentWriteReg = 0;
		}else{
				if(LaserNumber == LASER_NUMBER_CHAN_1 && SampCurType == SAMPCUR_TYPE_WORK_CURRENT){
				float seedVoltageCoel = 1.001722 * Current;
				float seedVoltage = seedVoltageCoel - 8.126;
				seedVolSet = seedVoltage;
				float seedCurrentWriteReg = (uint16_t)(seedVoltage / 1000 / (AD5541_VREF_TA) * AD5541_MAXCODE);
				return seedCurrentWriteReg;
			}else if(LaserNumber == LASER_NUMBER_CHAN_2 && SampCurType == SAMPCUR_TYPE_WORK_CURRENT){
				float taVoltageCoel = Current - 103.7;
				float taVoltage = taVoltageCoel / 1.588;
				currentWriteReg = (uint16_t)(taVoltage / 1000 / (AD5541_VREF_TA) * AD5541_MAXCODE);
				//return taCurrentWriteReg;
			}else if(LaserNumber == LASER_NUMBER_CHAN_2 && SampCurType == SAMPCUR_TYPE_PD_CURRENT){
				float pdVoltageCoel = Current * ADDA_R_PD;
				float pdVoltage = pdVoltageCoel;
				currentWriteReg = (uint16_t)(pdVoltage / (AD5541_VREF_TA) * AD5541_MAXCODE);
				//return taCurrentWriteReg;
			}
		}
		
#elif MODEL_CHOICE == MODEL_LASER_DFB
    float CurrentVolage      = Current * ADDA_R_SEED;
    uint16_t CurrentWriteReg = (uint16_t)(CurrentVolage / 1000 / AD5541_VREF_SEED * AD5541_MAXCODE);
#endif
		//return currentWriteReg;
}
*/


uint16_t hal_DAC5541SpiCurrentmAToReg(float Current, int LaserNumber)
{
// DAC5541的输出分种子和TA
// 种子的电阻：10欧姆
// TA的电阻：300欧姆
#if MODEL_CHOICE == MODEL_LASER_TA
	
		if(LaserNumber == LASER_NUMBER_CHAN_1){
				float seedVoltageCoel = 1.01722 * Current;
				float seedVoltage = seedVoltageCoel - 8.126;
			
				seedVolSet = seedVoltage;
				
				if(seedVoltage <= 0){
					seedVoltage = 0;
				}
				
				
				
				//seedVoltage = 993;
				//float seedVoltage = Current;
			
				seedVolSet = seedVoltage;
				
				float seedCurrentWriteReg = (uint16_t)(seedVoltage / 1000 / (AD5541_VREF_SEED) * AD5541_MAXCODE);
				return seedCurrentWriteReg;
			}else if(LaserNumber == LASER_NUMBER_CHAN_2){
				//float taVoltageCoel = Current - 103.7;
				//float taVoltage = taVoltageCoel / 1.588;
				float taVoltage = Current;
				taVolSet = taVoltage;
				float taCurrentWriteReg = (uint16_t)(taVoltage / 1000 / (AD5541_VREF_TA) * AD5541_MAXCODE);
				return taCurrentWriteReg;
			}
	
    //float CurrentVolage      = Current * ((LaserNumber == LASER_NUMBER_CHAN_1) ? ADDA_R_SEED : ADDA_R_PD);
    //uint16_t CurrentWriteReg = (uint16_t)(CurrentVolage / 1000 / ((LaserNumber == LASER_NUMBER_CHAN_1) ? AD5541_VREF_SEED : AD5541_VREF_TA) * AD5541_MAXCODE);
#elif MODEL_CHOICE == MODEL_LASER_DFB
    float CurrentVolage      = Current * ADDA_R_SEED;
    uint16_t CurrentWriteReg = (uint16_t)(CurrentVolage / 1000 / AD5541_VREF_SEED * AD5541_MAXCODE);
#endif

    //return CurrentWriteReg;
}
